<?php 
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Category;
use Illuminate\Http\Request;
use App\Friend;
class FriendController extends Controller{
	function add(){
		$cateArr = Category::getTree();
		return view('admin.friend.add',['cateArr'=>$cateArr]);
	}
	function doadd(Request $request){
		$arr = $request->all();

		if($arr['upload']){
			$path = $arr['upload']->store('friend','my');
		}else{
			$path = '';
		}
		$arr['flogo']=$path;
		$re = Friend::create($arr);
		$message = is_object($re) ? "保存成功" : "保存失败";
		return redirect()->back()->with('message',$message);
	}
	function index(){
		$cols = Friend::select('friend.*','category.cname')
		->leftJoin('category','friend.cid','=','category.id')
		->orderBy('friend.id','desc')->paginate(2);
		return view('admin.friend.index',['cols'=>$cols]);
	}
	function edit($id){
		$cateArr = Category::getTree();
		$ob = Friend::find($id);
		return view('admin.friend.edit',['ob'=>$ob,'cateArr'=>$cateArr]);
	}
	function doedit(Request $request){
		$arr = $request->all();
		if(isset($arr['upload'])){
			$path = $arr['upload']->store('friend','my');
			$arr['flogo']=$path;
			//删除原理的图片
			if(!empty($arr['oldpath'])){
				@unlink("./upload/".$arr['oldpath']);
			}
		}
		unset($arr['oldpath']);
		unset($arr['_token']);
		unset($arr['upload']);
		$re = Friend::where('id',$arr['id'])->update($arr);
		$message = $re ? "修改成功" : "修改失败";
		return redirect('admin/friend/index')->with('message',$message);
	}
	function del($id){
		$ob = Friend::find($id);
		$path = $ob->flogo;
		if(!empty($path)){
			@unlink('./upload/'.$path);
		}
		$row = $ob->delete();
		$message = $row ? "删除成功" : "删除失败";
		return redirect()->back()->with('message',$message);
	}
}